package com.lds.erp.gateway.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lds.erp.base.RequestWrapper;

/**
 * @author hongsir
 * @apiNote 跨域处理
 * @date 2018/5/18 下午3:21
 */
//@WebFilter(urlPatterns = {"/api/*"})
public class FilterCross implements Filter {
    private static final Logger log = LoggerFactory.getLogger(FilterCross.class);

    public FilterCross() {
        log.info("========初始化跨域处理过滤器========");
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletrequest;
        HttpServletResponse response = (HttpServletResponse) servletresponse;

        //打印所有head和入参
//        String date = DateUtils.allDate(new Date());
//        System.out.println("***************begin*" + date + "*" + request.getMethod() + "************");
//        Enumeration<String> headers = request.getHeaderNames();
//        while (headers.hasMoreElements()) {
//            String headerName = headers.nextElement();
//            String headerValue = request.getHeader(headerName);
//            System.out.println(headerName + "=" + headerValue);
//        }
        if (FilterConstants.CONVERT_METHOD.equalsIgnoreCase(request.getMethod())) {
            request = new RequestWrapper(request);
//            System.out.println("post参数:" + ((RequestWrapper) request).getBody());
        } else {
//            System.out.println("get参数:" + JSON.toJSONString(AppUtils.getRequestMap(request)));
        }
//        System.out.println("***************end*" + date + "*" + request.getMethod() + "*************");

        // 解决rest中文乱码问题
        request.setCharacterEncoding("UTF-8");

        // 解决ajax跨域问题
        String origin = request.getHeader("origin");
        log.info("1跨域检测>method:{}\turl:{}\torigin:{}", request.getMethod(), request.getRequestURI(), origin);
        response.setHeader("Access-Control-Allow-Origin", StringUtils.isNotBlank(origin) ? origin : "*");
        // 允许跨域请求获取header
        response.setHeader("Access-Control-Expose-Headers", "token,isign,app,x-requested-with,content-type,No-Cache");
        response.setHeader("Access-Control-Request-Method", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Request-Headers", "token,isign,app,x-requested-with,content-type,No-Cache");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "token,isign,app,x-requested-with,content-type,No-Cache");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // 如果是OPTIONS跨域预检请求，返回成功
        if (FilterConstants.CROSS_METHOD.equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.SC_OK);
            response.getWriter().write("跨域检测通过!");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
